package vn.bang.xiangqi.server.business;

import java.util.Date;

import javax.persistence.EntityManager;

import vn.bang.dao.DAOFactory;
import vn.bang.dao.UserDAO;
import vn.bang.entity.UserDTO;
import vn.bang.utility.DateUtil;
import vn.bang.utility.JpaUtil;


public class LoginBusiness extends AbstractBaseBusiness {

	static public UserDTO login(String username, String password) {
		EntityManager entityManager = createEntityManager();
		UserDTO user = null;
		try {
			JpaUtil.beginTransaction(entityManager);
			user = findByUsername(username, entityManager);
			if (null == user || !password.equals(user.getPassword())) {
				return null;
			}
			updateLastTime(user, DateUtil.getNow(), entityManager);
			JpaUtil.commitEntityManager(entityManager);
			
		} finally {
			JpaUtil.closeEntityManager(entityManager);
		}
		return user;
	}

	static public UserDTO updateLastTime(UserDTO user, Date date, EntityManager entityManager) {
		UserDAO userDAO = DAOFactory.createUserDAO(entityManager);
		user.setLastLoginTime(date);
		return userDAO.merge(user);
	}

	private static UserDTO findByUsername(String username, EntityManager entityManager) {
		UserDAO userDAO = DAOFactory.createUserDAO(entityManager);
		return userDAO.findActiveByUsername(username);
	}
	
}
